var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken');
const { verifyToken, judgeToken, decodeToken } = require('../../tool/jwt')
const { setDate } = require('../../tool/date');
var request = require("request");
const { getLogisticsCode } = require('../../tool/logistics');

//引入支付宝沙箱配置
const alipaySdk = require('../../tool/alipay');
const AlipayFormData = require('alipay-sdk/lib/form').default;

//验证token方法
const tokenvalidate = (req, res, next) => {
    try {
        const token = req.headers.token;
        const v = verifyToken(token, 'shop_key')

        if (v != null) {
            const v2 = judgeToken(token, 'shop_key')

            if (v2 == 0) {
                next()
            } else {

                return res.send({ data: { msg: 'token已过期', code: '500' } })
            }

        } else {
            return res.send({ data: { msg: 'token已过期', code: '500' } })
        }

    } catch (error) {
        console.log(error)
        res.status(500).send('Error');
        process.exit(1)
    }
}

module.exports = (pool) => {

    //获取买到的订单列表 --- 用户购买的
    router.get('/getOrderListBuy/:type', (req, res, next) => { tokenvalidate(req, res, next) }, async (req, res) => {
        try {
            const { type } = req.params;
            const user = decodeToken(req.headers.token);
            if (user == null) return res.send({ data: { msg: 'token已过期', code: 500 } });
            const connection = await pool.promise().getConnection();
            if (type != 5) {
                const result = await connection.query(`select orders.*,goods.description,goods.url,user.nickname from orders join goods on goods.id = orders.gid join user on user.id = goods.uid where orders.uid =? and orders.order_status=? `, [user.id, type])
                connection.release();
                res.send({ data: { msg: '获取订单列表成功', code: 200, data: result[0] } })
            } else {
                const result = await connection.query(`select orders.*,goods.description,goods.url,user.nickname from orders join goods on goods.id = orders.gid join user on user.id = goods.uid where orders.uid =?`, [user.id])
                connection.release();
                res.send({ data: { msg: '获取订单列表成功', code: 200, data: result[0] } })
            }

        } catch (error) {
            console.error(error);
            res.status(500).send({ data: { msg: "服务异常", code: 500 } });
            process.exit(1)
        }
    })

    //获取卖出的订单列表 --- 用户卖出的
    router.get('/getOrderListSell/:type', (req, res, next) => { tokenvalidate(req, res, next) }, async (req, res) => {
        try {
            const { type } = req.params;
            const user = decodeToken(req.headers.token);
            if (user == null) return res.send({ data: { msg: 'token已过期', code: 500 } });
            const connection = await pool.promise().getConnection();

            if (type != 5) {
                const result = await connection.query(`select orders.*,user.nickname,goods.url,goods.description from goods JOIN orders on orders.gid = goods.id JOIN user on user.id = goods.uid where goods.uid = ? and orders.order_status = ? `, [user.id, type])
                connection.release();
                res.send({ data: { msg: '获取订单列表成功', code: 200, data: result[0] } })
            } else {
                const result = await connection.query(`select orders.*,user.nickname,goods.url,goods.description from goods JOIN orders on orders.gid = goods.id JOIN user on user.id = goods.uid where goods.uid = ?`, [user.id])
                connection.release();
                res.send({ data: { msg: '获取订单列表成功', code: 200, data: result[0] } })
            }

        } catch (error) {
            console.error(error);
            res.status(500).send({ data: { msg: "服务异常", code: 500 } });
            process.exit(1)
        }
    })

    //获取用户发布的商品
    router.get('/getshop/:type', (req, res, next) => { tokenvalidate(req, res, next) }, async (req, res) => {
        try {
            const { type } = req.params;
            // 获取用户信息
            const user = decodeToken(req.headers.token);
            if (user == null) return res.send({ data: { msg: 'token已过期', code: 500 } });
            const connection = await pool.promise().getConnection();
            const result1 = await connection.query('select * from goods where uid = ? and state = ?', [user.id, type])
            connection.release()
            res.send({ data: { msg: "获取成功", code: 200, data: result1[0] } })
        } catch (error) {
            console.error(error);
            res.status(500).send({ data: { msg: "服务异常", code: 500 } });
            process.exit(1)
        }
    })
    //下架商品
    router.get('/downshop/:id/:type', (req, res, next) => { tokenvalidate(req, res, next) }, async (req, res) => {
        try {
            //type 0 下架 1上架
            const { id, type } = req.params;
            const connection = await pool.promise().getConnection();
            if (type == 0) {
                const result = await connection.query('update goods set state = 0 where id = ?', [id])
                connection.release()
                if (result[0].affectedRows == 1) {
                    res.send({ data: { msg: "下架成功", code: 200 } })
                } else {
                    res.send({ data: { msg: "下架失败", code: 500 } })
                }
            } else {
                const result = await connection.query('update goods set state = 1 where id = ?', [id])
                connection.release()
                if (result[0].affectedRows == 1) {
                    res.send({ data: { msg: "上架成功", code: 200 } })
                } else {
                    res.send({ data: { msg: "上架失败", code: 500 } })
                }
            }

        } catch (error) {
            console.error(error);
            res.status(500).send({ data: { msg: "服务异常", code: 500 } });
            process.exit(1)
        }
    })
    //商家发货
    router.post('/sendgoods', (req, res, next) => { tokenvalidate(req, res, next) }, async (req, res) => {
        try {
            const {oid,company,number} = req.body;
            const connection = await pool.promise().getConnection();
            const result = await connection.query('update orders set order_status = 2,shipping_company = ?,shipping_number = ?,shipping_time =? where id = ?', [company,number,setDate(),oid])
            connection.release()
            if (result[0].affectedRows == 1) {
                res.send({ data: { msg: "发货成功", code: 200 } })
            }else {
                res.send({ data: { msg: "发货失败", code: 500 } })
            }
        } catch (error) {
            console.error(error);
            res.status(500).send({ data: { msg: "服务异常", code: 500 } });
            process.exit(1)
        }
    })
    //支付订单
    router.post('/payorder', (req, res, next) => { tokenvalidate(req, res, next) }, async (req, res) => {
        try {
            const {oid,zong} = req.body;
            const formData = new AlipayFormData();
            //调用get方法
            formData.setMethod('get'),
                //支付时 的信息
                formData.addField('bizContent', {
                    outTradeNo: oid,//订单号
                    productCode: 'FAST_INSTANT_TRADE_PAY',//固定
                    totalAmount: zong,//金额
                    subject: '商品名称'//商品名称
                });

            formData.addField('notifyUrl', 'http://edrwuk.natappfree.cc/shop/payment/callback');
            //支付成功或者失败打开的页面
            formData.addField('returnUrl', 'http://localhost:3000');
            const result2 = alipaySdk.exec(
                'alipay.trade.page.pay',
                {},
                { formData: formData },
            );
            result2.then(resp => {
                res.send({
                    data: {
                        code: 200,
                        success: true,
                        order: oid,
                        paymentUrl: resp
                    }
                })
            })
        } catch (error) {
            console.error(error);
            res.status(500).send({ data: { msg: "服务异常", code: 500 } });
            process.exit(1)
        }
    })

    //查看订单物流
    router.post('/logistics', (req, res, next) => { tokenvalidate(req, res, next) }, async (req, res) => {
        try {
            const {id} = req.body;
            const connection = await pool.promise().getConnection();
            const result = await connection.query('select shipping_number,shipping_company from orders where id = ?', [id])
            connection.release()
            const LogisticsCode = getLogisticsCode(result[0][0].shipping_company)
            var requestInfo = {
                method: "POST",
                url: "https://eolink.o.apispace.com/wlgj1/paidtobuy_api/trace_search",
                headers: {
                   "X-APISpace-Token": "101e03pr28lqa8y0ncs29gjds6rwdck8",
                   "Content-Type": "application/json"
                },
                body: JSON.stringify({  // 这里使用 JSON.stringify 来构造请求体
                   cpCode: LogisticsCode,       // 使用双引号
                   mailNo: result[0][0].shipping_number, // 使用双引号
                   tel: null,
                   orderType: null
                })
             };
             
             request(requestInfo, function (error, response, body) {
                 if (error){
                    res.send({ data: { msg: "查询失败", code: 500 } })
                   throw new Error(error);
                 }    
                //  console.log(body);
                 res.send({ data: { msg: "查询成功", code: 200, data: JSON.parse(body) } })
              
             });
           
        } catch (error) {
            console.error(error);
            res.status(500).send({ data: { msg: "服务异常", code: 500 } });
            process.exit(1)
        }
    })
    //确认收货
    router.get('/confirm/:id', (req, res, next) => { tokenvalidate(req, res, next) }, async (req, res) => {
        try {
            const {id} = req.params;
            const connection = await pool.promise().getConnection();
            const result = await connection.query('update orders set order_status = 3 where id = ?', [id])
            connection.release()
            if (result[0].affectedRows == 1) {
                res.send({ data: { msg: "确认收货成功", code: 200 } })
            }else{
                res.send({ data: { msg: "确认收货失败", code: 500 } })
            }
            
        } catch (error) {
            console.error(error);
            res.status(500).send({ data: { msg: "服务异常", code: 500 } });
            process.exit(1)
        }
    })

    //进程崩溃，关闭数据库连接
    process.on('SIGINT', () => {
        pool.end();
        redis.disconnect();
        process.exit(0);
    })
    return router;
}